<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入业务单据号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库" prop="scId" label-width="150px">
        <el-select v-model="queryParams.scId" placeholder="全部" clearable >
          <el-option v-for="(item, index) in center" :key="index" :label="item.name"
                     :value="item.id" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="盘点状态" prop="takeStatus" label-width="150px">
        <el-select v-model="queryParams.takeStatus" clearable placeholder="全部" style="width: 100%">
          <el-option label="盘点任务生成" value="0" ></el-option>
          <el-option label="盘点差异生成" value="1" ></el-option>
          <el-option label="盘点完成" value="2" ></el-option>
          <el-option label="盘点已作废" value="3" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建人" prop="createBy">
        <el-select v-model="queryParams.createById" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in user" :key="index" :label="item.name"
                     :value="item.id" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime" label-width="150px">
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="操作人" prop="updateBy" label-width="150px">
        <el-select v-model="queryParams.updateById" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in user" :key="index" :label="item.name"
                     :value="item.id" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="操作时间" prop="updateTime">
        <el-date-picker clearable
          v-model="queryParams.updateTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择修改时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label-width="150px">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:TakeStockPlan:add']"
        >新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:TakeStockPlan:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="TakeStockPlanList" @selection-change="handleSelectionChange">
      <el-table-column label="业务单据号" align="left" prop="code" width="200px"/>
      <el-table-column label="仓库名称" align="left" prop="center.name" width="100px" />
      <el-table-column label="盘点类别" align="left" prop="takeType" width="100px" >
        <template slot-scope="scope">
          <span>{{ scope.row.takeType==0 ? "全场盘点":scope.row.takeType==1 ? "单品盘点":scope.row.takeType==2 ? "类目盘点":"品牌盘点" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="盘点内容" align="left" prop="bizName" width="150px" />
      <el-table-column label="盘点状态" align="left" prop="takeStatus" width="150px" >
        <template slot-scope="scope">
          <span>{{ scope.row.takeStatus==0 ? "盘点任务生成":scope.row.takeStatus==6 ? "盘点差异生成":scope.row.takeStatus==9 ? "盘点完成":"盘点已作废" }}</span>
        </template>
      </el-table-column>
x      <el-table-column label="创建人" align="left" prop="createBy" width="100"/>
      <el-table-column label="创建时间" align="left" prop="createTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="left" prop="updateBy" width="100" />
      <el-table-column label="操作时间" align="left" prop="updateTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="left" prop="description" />
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" fixed="right" width="200px">
        <template slot-scope="scope">
          <el-button
            size="medium"
            type="text"
            @click="selectTakeStockSheet(scope.row,'查看')"
            v-hasPermi="['system:PurchaseOrder:edit']"
          >查看</el-button>
          <el-button
            size="medium"
            type="text"
            v-if="scope.row.takeStatus == 0"
            @click="selectTakeStockSheet(scope.row,'差异生成')"
            v-hasPermi="['system:PurchaseOrder:edit']"
          >差异生成</el-button>
          <el-button
            size="medium"
            type="text"
            v-if="scope.row.takeStatus == 6"
            @click="selectTakeStockSheet(scope.row,'差异处理')"
            v-hasPermi="['system:PurchaseOrder:edit']"
          >差异处理</el-button>
          <el-button
            size="medium"
            type="text"
            style="color: red"
            v-if="scope.row.takeStatus ==6 || scope.row.takeStatus ==0"
            @click="statusUpdate(scope.row)"
          >作废</el-button>
          <el-button
            size="medium"
            type="text"
            style="color: red"
            v-if="scope.row.takeStatus == 12"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:PurchaseOrder:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加库存盘点任务对话框 -->
    <el-dialog title="新增" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px" >
        <el-form-item label="仓库" prop="scId">
          <el-select v-model="form.scId" clearable style="width: 100%">
            <el-option v-for="(item, index) in center" :key="index" :label="item.name"
                       :value="item.id" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="盘点类型" prop="takeType">
          <el-select v-model="form.takeType" @change="openReset" clearable style="width: 100%">
            <el-option label="全场盘点" value="0" ></el-option>
            <el-option label="单品盘点" value="1" ></el-option>
            <el-option label="类目盘点" value="2" ></el-option>
            <el-option label="品牌盘点" value="3" ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="品牌" prop="createById" v-if="form.takeType == 3">
          <input v-model="this.brandNames" @click="selectBrand"
                 style="border-radius: 5px;border: 1px gainsboro solid;width: 100%;height: 35px"/>
        </el-form-item>

        <el-form-item label="类目" prop="createById" v-if="form.takeType == 2">
          <input v-model="this.categoryNames" @click="selectCategory"
                 style="border-radius: 5px;border: 1px gainsboro solid;width: 100%;height: 35px"/>
        </el-form-item>

        <el-form-item label="备注" prop="description">
          <el-input type="textarea" v-model="form.description"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--    类目弹窗-->
    <el-dialog title="商品类目" :visible.sync="categoryOpen" width="800px">
      <el-form :model="categoryQueryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <div style="border: 1px #d1dbe5 solid;height: 80px">
          <el-form-item label="名称" prop="name" style="margin-top: 20px">
            <el-input
              v-model="categoryQueryParams.name"
              placeholder="请输入名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="状态" prop="takeStatus" label-width="100px" style="margin-top: 20px">
            <el-select v-model="categoryQueryParams.available" clearable placeholder="全部" style="width: 100%">
              <el-option label="启用" value="1" ></el-option>
              <el-option label="停用" value="0" ></el-option>
            </el-select>
          </el-form-item>
        </div>

        <el-form-item  style="margin-top: 20px">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="categoryQuery">搜索</el-button>
        </el-form-item>
      </el-form>

      <div style="border: 1px #d1dbe5 solid">
        <el-table v-loading="loading" :data="categoryList" @selection-change="handleSelectionChange">
          <el-table-column type="selection"></el-table-column>
          <el-table-column label="名称" align="left" prop="name" width="500px"/>
          <el-table-column label="状态" align="left" prop="available" width="200">
            <template slot-scope="scope">
              <span>{{ scope.row.available==1?"启用":"停用" }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="categoryOpen = false">取 消</el-button>
        <el-button type="primary"  @click="confirmSelection">确 定</el-button>
      </div>
    </el-dialog>

    <!--    品牌弹窗-->
    <el-dialog title="商品品牌" :visible.sync="brandOpen" width="900px">
      <el-form :model="brandQueryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <div style="border: 1px #d1dbe5 solid;height: 80px">
          <el-form-item label="编号" prop="name" style="margin-top: 20px">
            <el-input
              v-model="brandQueryParams.code"
              placeholder="请输入编号"
              clearable
            />
          </el-form-item>
          <el-form-item label="名称" prop="name" style="margin-top: 20px">
            <el-input
              v-model="brandQueryParams.name"
              placeholder="请输入名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="状态" prop="takeStatus" style="margin-top: 20px">
            <el-select v-model="brandQueryParams.available" clearable placeholder="全部" style="width: 100%">
              <el-option label="启用" value="1" ></el-option>
              <el-option label="停用" value="0" ></el-option>
            </el-select>
          </el-form-item>
        </div>

        <el-form-item  style="margin-top: 20px">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="brandQuery">搜索</el-button>
        </el-form-item>
      </el-form>

      <div style="border: 1px #d1dbe5 solid">
        <el-table v-loading="loading" :data="brandList" @selection-change="brandSelectionChange">
          <el-table-column type="selection"></el-table-column>
          <el-table-column label="编号" align="left" prop="code" width="150px"/>
          <el-table-column label="名称" align="left" prop="name" width="450px"/>
          <el-table-column label="状态" align="left" prop="available" width="200">
            <template slot-scope="scope">
              <span>{{ scope.row.available==1?"启用":"停用" }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="brandOpen = false">取 消</el-button>
        <el-button type="primary"  @click="brandConfirmSelection">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 查看弹窗 -->
    <el-dialog :title="selectTitle" :visible.sync="selectOpen" width="1000px" append-to-body>
      <div style="border: 1px gainsboro solid;padding: 10px 10px 10px 30px">
        <div style="display: inline-block;width: 300px;"><p>仓库：{{ this.selectForm.center.name }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>盘点类别：{{ this.selectForm.takeType==0 ? "全场盘点":this.selectForm.takeType==1 ? "单品盘点":this.selectForm.takeType==2 ? "类目盘点":"品牌盘点" }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>盘点状态：{{ this.selectForm.takeStatus==0 ? "盘点任务生成":this.selectForm.takeStatus==6 ? "盘点差异生成":this.selectForm.takeStatus==9 ? "盘点完成":"盘点已作废" }}</p></div>
        <br>
        <div style="display: inline-block;width: 800px;">备注：<textarea style="width:90%;height: 50px;border-radius: 5px;vertical-align:middle;border: 1px gainsboro solid" v-model="this.selectForm.description" :disabled="this.selectForm.takeStatus!=6"/></div>
        <br>
        <div style="display: inline-block;width: 300px;"><p>创建人：{{ this.selectForm.createBy }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>创建时间：{{ this.selectForm.createTime }}</p></div>
        <br>
        <div style="display: inline-block;width: 300px;"><p>操作人：{{ this.selectForm.updateBy }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>操作时间：{{ this.selectForm.updateTime }}</p></div>
      </div>

      <div style="margin: 10px 0">
        筛选时间：
        <el-checkbox v-model="checkbox1" @change="updateSelect">报损数据</el-checkbox>
        <el-checkbox v-model="checkbox2" @change="updateSelect">报溢数据</el-checkbox>
        <el-checkbox v-model="checkbox3" @change="updateSelect">无损溢数据</el-checkbox>
      </div>

      <div style="border: 1px gainsboro solid;margin-top: 5px">
        <el-table height="400px" v-loading="loading" :data="this.tblTakeStockPlanDetailList" @selection-change="handleSelectionChange">
          <el-table-column label="商品编号" align="left" prop="baseDataProduct.code" width="100px"/>
          <el-table-column label="商品名称" align="left" prop="baseDataProduct.name" width="200px"/>
          <el-table-column label="单位" align="left" prop="baseDataProduct.unit" width="100px"/>
          <el-table-column label="规格" align="left" prop="baseDataProduct.spec" width="100px"/>
          <el-table-column label="商品类目" align="left" prop="baseDataProduct.baseDataProductCategory.name" width="100px"/>
          <el-table-column label="商品品牌" align="left" prop="baseDataProduct.baseDataProductBrand.name" width="100px"/>

          <el-table-column label="系统库存数量" align="left" prop="stockNum" width="100px"/>
          <el-table-column label="盘点数量" align="left" prop="oriTakeNum" width="100px"/>
          <el-table-column
            label="修改后盘点数量"
            align="left"
            prop="takeNum"
            width="150px"
            v-if="selectTitle == '查看' || (selectForm.takeStatus === 6 && selectTitle != '查看')">
            <template slot-scope="scope">
              <!-- 根据状态判断是否可编辑 -->
              <div v-if="selectTitle == '查看'">
                {{ scope.row.takeNum }}
              </div>
              <div v-else-if="selectForm.takeStatus === 6 && selectTitle != '查看'">
                <el-input
                  v-model="scope.row.takeNum"
                  @input="() => updateDifference(scope.row)"
                />
              </div>
            </template>
          </el-table-column>

          <el-table-column label="出项数量" align="left" prop="totalOutNum" width="100px"/>
          <el-table-column label="进项数量" align="left" prop="totalInNum" width="100px"/>
          <el-table-column label="盘点差异数量" align="left" prop="" width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.firstSecondDiff || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="备注"
            align="left"
            prop="description"
            width="150px"
            v-if="selectTitle == '查看' || (selectForm.takeStatus === 6 && selectTitle != '查看')">
            <template slot-scope="scope">
              <!-- 根据状态判断是否可编辑 -->
              <div v-if="selectTitle == '查看'">
                {{ scope.row.description }}
              </div>
              <div v-else-if="selectForm.takeStatus === 6 && selectTitle != '查看'">
                <el-input
                  v-model="scope.row.description"
                />
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div slot="footer" class="dialog-footer" style="text-align: center" v-if="this.selectTitle!='查看'">
        <el-button @click="selectOpen = false">取 消</el-button>
        <el-button type="primary" v-if="this.selectForm.takeStatus===0" @click="getTakeStockPlanStatus">差异生成</el-button>
        <el-button type="primary" v-if="this.selectForm.takeStatus===6" @click="getTakeStockPlanStatus">差异处理</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTakeStockPlan, getTakeStockPlan, delTakeStockPlan, addTakeStockPlan, updateTakeStockPlan } from "@/api/system/TakeStockPlan";
import {center, user} from "@/api/system/order";
import {listProductCategory} from "@/api/system/ProductCategory";
import {listProductBrand} from "@/api/system/ProductBrand";
import {listProductInfo} from "@/api/system/ProductInfo";
import {listStock} from "@/api/system/stock";
import {parseTime} from "../../../utils/ruoyi";

export default {
  name: "TakeStockPlan",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedTblTakeStockPlanDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,

      // 库存盘点任务表格数据
      TakeStockPlanList: [],
      // 库存盘点任务明细表格数据
      tblTakeStockPlanDetailList: [],

      //库存任务ID数据
      tblTakeStockPlanIds:[],
      //库存任务详情ID数据
      tblTakeStockPlanDetailIds:[],

      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        scId: null,
        takeStatus: null,
        createById: null,
        createTime: null,
        updateById: null,
        updateTime: null
      },
      // 表单参数
      form: {},

      // 仓库下拉框
      center: [],
      // 用户(审核人、操作人、销售员)下拉框
      user: [],

      //商品数据
      productList:[],

      //商品类目
      categoryOpen:false,
      categoryQueryParams:{},
      categoryList:[],
      categorySelectedRows: [],
      categoryNames:'',

      //商品品牌
      brandOpen:false,
      brandQueryParams:{},
      brandList:[],
      brandSelectedRows: [],
      brandNames:'',

      //查看数据详情
      selectOpen:false,
      selectTitle:'',
      selectForm:{
        center:{
          name:""
        }
      },
      selectTblTakeStockPlanDetailList:[],

      //盘点状态
      checkbox1:true,
      checkbox2:true,
      checkbox3:true,
    };
  },
  created() {
    this.selectProduct();
    this.categoryQuery();
    this.brandQuery();

    this.getList();
  },
  methods: {
    parseTime,
    /** 查询库存盘点任务列表 */
    getList() {
      this.loading = true;
      listTakeStockPlan(this.queryParams).then(response => {
        this.TakeStockPlanList = response.rows;
        this.total = response.total;

        //获取盘点内容
        for (let i = 0; i < this.TakeStockPlanList.length; i++) {
          let ids=this.TakeStockPlanList[i].bizId.split(",");
          let name='';
          if (this.TakeStockPlanList[i].takeType==2){
            for (let k = 0; k < ids.length; k++) {
              for (let j = 0; j < this.categoryList.length; j++) {
                if (this.categoryList[j].id==ids[k]){
                  name+=this.categoryList[j].name;
                  if (k<ids.length-1)
                    name+='，';
                }
              }
            }
          }else if (this.TakeStockPlanList.takeType==3){
            for (let k = 0; k < ids.length; k++) {
              for (let j = 0; j < this.brandList.length; j++) {
                if (this.brandList[j].id==ids[k]){
                  name+=this.brandList[j].name;
                  if (k<ids.length-1)
                    name+='，';
                }
              }
            }
          }

          this.TakeStockPlanList[i].bizName=name;
        }

        //获取所有任务和任务详情的ID数据
        for (var i=0;i<this.TakeStockPlanList.length;i++){
          this.tblTakeStockPlanIds.push(this.TakeStockPlanList[i].id);
          for (var j=0;j<this.TakeStockPlanList[i].tblTakeStockPlanDetailList.length;j++){
            this.tblTakeStockPlanDetailIds.push(this.TakeStockPlanList[i].tblTakeStockPlanDetailList[j].id);
          }
        }
      });

      center(this.ck).then(response => {
        this.center = response.rows;
      });

      user(this.user).then(response => {
        this.user = response.rows;
      });

      this.loading = false;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.openReset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        scId: null,
        takeType: null,
        bizId: null,
        takeStatus: null,
        description: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null
      };
      this.tblTakeStockPlanDetailList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
    },
    /** 提交按钮 */
    async submitForm() {
      await this.insertTakeStockPlanDetail()
      const newId = generateUniqueId(this.tblTakeStockPlanIds);
      var code = getOrderCode(this.TakeStockPlanList);

      this.form.id=newId;
      this.form.code=code;
      this.form.takeStatus=0;
      if (this.form.takeType==2){
        let bizId="";
        for (let i = 0; i < this.categorySelectedRows.length; i++) {
          if (i<this.categorySelectedRows.length-1){
            bizId+=this.categorySelectedRows[i].id+",";
          }else {
            bizId+=this.categorySelectedRows[i].id;
          }
        }
        this.form.bizId=bizId;
      }else if (this.form.takeType==3){
        let bizId="";
        for (let i = 0; i < this.brandSelectedRows.length; i++) {
          if (i<this.brandSelectedRows.length-1){
            bizId+=this.brandSelectedRows[i].id+",";
          }else {
            bizId+=this.brandSelectedRows[i].id;
          }
        }
        this.form.bizId=bizId;
      }
      this.form.createBy="系统管理员";
      this.form.createById="1";
      this.form.updateBy="系统管理员";
      this.form.updateById="1";
      this.form.tblTakeStockPlanDetailList=this.tblTakeStockPlanDetailList

      addTakeStockPlan(this.form).then(response => {
        this.$modal.msgSuccess("新增成功");
        this.open = false;
        this.getList();
      });
    },

    async insertTakeStockPlanDetail(){
      this.tblTakeStockPlanDetailList=[];
      for (let i = 0; i < this.productList.length; i++) {
        let id=null;
        if (this.form.takeType==0){
          id=this.productList[i].id;
        }else if (this.form.takeType==2){
          for (let j = 0; j < this.categorySelectedRows.length; j++) {
            if (this.productList[i].categoryId==this.categorySelectedRows[j].id){
              id=this.productList[i].id;
            }
          }
        }else if (this.form.takeType==3){
          for (let j = 0; j < this.brandSelectedRows.length; j++) {
            if (this.productList[i].brandId==this.brandList[j].id){
              id=this.productList[i].id;
            }
          }
        }

        if (id!=null){
          const stock = await this.getProductStock(this.form.scId, id);
          const newId = generateUniqueId(this.tblTakeStockPlanDetailIds);
          this.tblTakeStockPlanDetailList.push({
            id: newId,
            planId:this.form.id,
            productId:id,
            stockNum:stock.stockNum||0,
            oriTakeNum:null,
            takeNum:null,
            totalOutNum:0,
            totalInNum:0,
            description:null,
            orderNo:this.tblTakeStockPlanDetailList.length+1,
          })
        }
      }
    },

    //商品库存
    async getProductStock(scId, productId) {
      try {
        const response = await listStock({ scId, productId });
        if (response.rows.length === 0) {
          return 0;
        }
        const stock = response.rows[0];
        return stock;
      }catch (error) {
        console.error('获取商品库存失败:', error);
        return null; // 返回 null 表示获取失败
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除库存盘点任务编号为"' + ids + '"的数据项？').then(function() {
        return delTakeStockPlan(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },


    /** 导出按钮操作 */
    handleExport() {
      this.download('system/TakeStockPlan/export', {
        ...this.queryParams
      }, `TakeStockPlan_${new Date().getTime()}.xlsx`)
    },

    //复选框返回
    handleSelectionChange(selection) {
      this.categorySelectedRows = selection;
    },
    confirmSelection() {
      this.categoryOpen = false;
      this.categoryNames = this.categorySelectedRows.map(item => item.name).join(',');
      // 返回选中的数据，可通过事件传递出去
      this.$emit('confirm', this.categorySelectedRows);
    },

    //复选框返回
    brandSelectionChange(selection) {
      this.brandSelectedRows = selection;
    },
    brandConfirmSelection() {
      this.brandOpen = false;
      this.brandNames = this.brandSelectedRows.map(item => item.name).join(',');
      // 返回选中的数据，可通过事件传递出去
      this.$emit('brandConfirm', this.brandSelectedRows);
    },

    //商品查询
    selectProduct(){
      listProductInfo({}).then(response => {
        this.productList = response.rows;
      })
    },

    //商品类目查询
    selectCategory(){
      this.categoryOpen = true;
      this.categoryQuery();
    },
    categoryQuery(){
      this.categoryList=[]
      listProductCategory(this.categoryQueryParams).then(response => {
        this.categoryList = response.rows;
      });
    },

    //商品品牌查询
    selectBrand(){
      this.brandOpen = true;
      this.brandQuery();
    },
    brandQuery(){
      this.brandList=[]
      listProductBrand(this.brandQueryParams).then(response => {
        this.brandList = response.rows;
      });
    },

    openReset(){
      this.categorySelectedRows = [];
      this.categoryList = [];
      this.categoryQueryParams = {};
      this.categoryNames='';

      this.brandSelectedRows = [];
      this.brandList = [];
      this.brandQueryParams = {};
      this.brandNames='';
    },

    // 查看按钮
    selectTakeStockSheet(row,title) {
      this.selectOpen = true;
      this.selectTitle=title;
      this.checkbox1=true;
      this.checkbox2=true;
      this.checkbox3=true;

      const id = row.id || this.ids
      getTakeStockPlan(id).then(response => {
        this.selectForm = response.data;
        this.selectTblTakeStockPlanDetailList=response.data.tblTakeStockPlanDetailList;
        this.selectOpen = true;

        this.tblTakeStockPlanDetailList=this.selectTblTakeStockPlanDetailList

        for (let i = 0; i < this.selectTblTakeStockPlanDetailList.length; i++) {
          this.updateDifference(this.selectTblTakeStockPlanDetailList[i])
        }
      });
    },

    //根据复选框选中状态来改变详情列表的数值显示
    updateSelect(){
      this.tblTakeStockPlanDetailList=[];

      for (let i = 0; i < this.selectTblTakeStockPlanDetailList.length; i++) {
        let stockNum=this.selectTblTakeStockPlanDetailList[i].stockNum||0;
        let oriTakeNum=this.selectTblTakeStockPlanDetailList[i].oriTakeNum||0;
        let takeNum=this.selectTblTakeStockPlanDetailList[i].takeNum||0;

        if ((oriTakeNum-stockNum<0 || takeNum-stockNum<0) && this.checkbox1){
          this.tblTakeStockPlanDetailList.push(this.selectTblTakeStockPlanDetailList[i])
          continue
        }
        if ((oriTakeNum-stockNum>0 || takeNum-stockNum>0) && this.checkbox2){
          this.tblTakeStockPlanDetailList.push(this.selectTblTakeStockPlanDetailList[i])
          continue
        }
        if ((oriTakeNum===stockNum || takeNum===stockNum) && this.checkbox3){
          this.tblTakeStockPlanDetailList.push(this.selectTblTakeStockPlanDetailList[i])
        }
      }
    },

    //状态修改
    getTakeStockPlanStatus(){

      if (this.selectTitle=="差异生成"){
        for (let i = 0; i < this.selectTblTakeStockPlanDetailList.length; i++) {
          this.selectTblTakeStockPlanDetailList[i].oriTakeNum=this.selectTblTakeStockPlanDetailList[i].oriTakeNum||0
          this.selectTblTakeStockPlanDetailList[i].takeNum=this.selectTblTakeStockPlanDetailList[i].takeNum||0
        }
        this.selectForm.takeStatus=6
      }else if (this.selectTitle=="差异处理"){
        this.selectForm.takeStatus=9
      }

      this.selectForm.tblTakeStockPlanDetailList=this.selectTblTakeStockPlanDetailList

      updateTakeStockPlan(this.selectForm).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.selectOpen=false;
        this.getList()
      });
    },

    // 自动计算差异值
    updateDifference(row) {
      if (row.stockNum != null && row.takeNum != null) {
        let diff1 = row.takeNum - row.stockNum;
        if (row.takeNum===0 || row.takeNum===null){
          diff1 = row.oriTakeNum - row.stockNum;
        }
        this.$set(row, 'firstSecondDiff', diff1);
      }
    },

    // 作废按钮点击事件
    statusUpdate(row) {
      this.$modal.confirm('是否确认作废该盘点任务？', {
        customClass: 'top-confirm-dialog'
      }).then(() => {
        const params = {
          id: row.id,
          takeStatus: 12 // 盘点已作废状态码
        };
        updateTakeStockPlan(params).then(response => {
          this.$modal.msgSuccess("任务已作废");
          this.getList(); // 刷新列表
        });
      }).catch(() => {});
    }

  }
};

// ID生成
function generateUniqueId(existingIds) {
  const prefix = '18';
  const length = 19 - prefix.length;
  const characters = '0123456789';
  let uniqueId;

  do {
    uniqueId = prefix;
    for (let i = 0; i < length; i++) {
      uniqueId += characters.charAt(Math.floor(Math.random() * characters.length));
    }
  } while (existingIds.includes(uniqueId));

  return uniqueId;
}


//单号生成
function getOrderCode(list) {
  var date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1, // 月份是从0开始的
    day = date.getDate();

// 如果月份或日期是个位数，在前面补0
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  var time=year + '' + month + '' + day

  let type="PDRW";    //盘点任务
  var code=time+'0000000'
  var str1=code.slice(0,7)
  var str2=code.slice(7,)

  if (str2.slice(0,1)=="0"){
    str1=code.slice(0,6)
    str2=code.slice(6,)

    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(6,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(6,)
        }
      }
    }
  }else {
    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(7,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(7,)
        }
      }
    }
  }

  code=type+str1+(parseInt(str2)+1)

  return code.toString();
}
</script>
